const express = require('express')
const service = require('./wallet.service')
const knexClient = require('../../../helper/knexClient')
const validateRequest = require('../../../middleware/validateRequest')
const hashBodyPassword = require('../../../middleware/hashBodyPassword')
const requireRequestContextRole = require('../../../middleware/requireRequestContextRole')
const validation = require('./wallet.validation')
const StatusCode = require('../../../constant/StatusCode')
const Role = require('../../../constant/Role')

const router = express.Router()
const routerPath = '/wallet'

router.get(
  routerPath,
  requireRequestContextRole(Role.ADMINISTRATOR),
  validateRequest(validation.find),
  async (req, res, next) => {
    try {
      const params = req.query
      const result = await service.find(knexClient, params, req.context)
      return res.json(result)
    } catch (error) {
      return next(error)
    }
  },
)

router.post(
  routerPath,
  requireRequestContextRole(Role.ADMINISTRATOR),
  validateRequest(validation.create),
  hashBodyPassword,
  async (req, res, next) => {
    try {
      const params = req.body
      const record = await service.create(knexClient, params, req.context)
      return res.status(StatusCode.CREATED).json(record)
    } catch (error) {
      return next(error)
    }
  },
)

router.get(
  `${routerPath}/:id`,
  requireRequestContextRole(Role.ADMINISTRATOR),
  validateRequest(validation.get),
  async (req, res, next) => {
    try {
      const { id } = req.params
      const params = req.query
      const record = await service.get(knexClient, id, params, req.context)
      return res.json(record)
    } catch (error) {
      return next(error)
    }
  },
)

router.patch(
  `${routerPath}/:id`,
  requireRequestContextRole(Role.ADMINISTRATOR),
  validateRequest(validation.update),
  hashBodyPassword,
  async (req, res, next) => {
    try {
      const { id } = req.params
      const params = req.body
      const record = await service.update(knexClient, id, params, req.context)
      return res.json(record)
    } catch (error) {
      return next(error)
    }
  },
)

router.delete(
  `${routerPath}/:id`,
  requireRequestContextRole(Role.ADMINISTRATOR),
  validateRequest(validation.delete),
  async (req, res, next) => {
    try {
      const { id } = req.params
      const success = await service.remove(knexClient, id, req.context)
      return res.json({ success })
    } catch (error) {
      return next(error)
    }
  },
)

module.exports = router
